package com.studerb.tasks.headers;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;

import com.studerb.model.Header;
import com.studerb.model.NewsGroup;
import com.studerb.util.Constants;

public class DLAllHeadersConsumerTask implements Runnable {
    private BlockingQueue<String> queue;
    private NewsGroup group;
    Logger logger = Logger.getLogger(DLAllHeadersConsumerTask.class);

    public DLAllHeadersConsumerTask(BlockingQueue<String> q, NewsGroup group) {
        this.queue = q;
        this.group = group;
    }

    public void run() {
        String line;
        List<Header> tempHeaders = new ArrayList<Header>();
        int count = 0;
        int rejected = 0;

        while(true){
            try{
                line = queue.take();
            }
            catch(InterruptedException e){
                logger.debug("interrupted");
                return;
            }
            if( ++count % DLAllHeadersTask.LOG_COUNT == 0)
                logger.debug(count + ": " + line);

            // end of queue - finish updating to database last groups
            if(line.equals(Constants.END_OF_QUEUE)){
                logger.info("Received END_OF_QUEUE: " + line);
                break;
            }

            // create a new Header by parsing the string
            Header header = Header.createHeader(line);
            if(header == null){
                ++rejected;
            }
            else{
                tempHeaders.add(header);
            }
        }
        logger.debug("Finished obtaining headers. Should have gotten: " + group.getPostsCount() + " headers.");
        logger.debug("Rejected " + rejected + " headers");
        logger.debug("Obtained " + tempHeaders.size() + " good headers.");
    }
}
